<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Draw Demo</title>
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0"/>
    <link rel="stylesheet" href="/js/jquery.mobile-1.2.0.min.css"/>
    <script src="/js/jquery-1.8.0.min.js"></script>
    <script src="/js/jquery.mobile-1.2.0.min.js"></script>
    <script src="/js/push-client-1.0.js"></script>
    <script src="/js/jquery.cookie.js"></script>
    <style type="text/css">
        body {
            margin: 0px;
            width: 100%;
            height: 100%;
            overflow: hidden;
            /* prevent text selection on ui */
            user-select: none;
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            /* prevent scrolling in windows phone */
            -ms-touch-action: none;
        }

        #content {
            overflow: hidden;
            background-color: #ddd;
        }

        #canvas {
            cursor: crosshair;
            background-color: #fff;
        }

        .palette-case {
            width: 260px;
            margin: auto;
            text-align: center;
        }

        .palette-box {
            float: left;
            padding: 2px 6px 2px 6px;
        }

        .palette {
            border: 2px solid #777;
            height: 36px;
            width: 36px;
        }

        .red {
            background-color: #c22;
        }

        .blue {
            background-color: #22c;
        }

        .green {
            background-color: #2c2;
        }

        .white {
            background-color: #fff;
        }

        .black {
            background-color: #000;
            border: 2px dashed #fff;
        }
    </style>
</head>
<script type="text/javascript">

    var id = Math.floor(Math.random() * 10000000);
    var ctx, color = "#000000";
    var dots = 0;
    $(document).ready(function () {

        // setup a new canvas for drawing wait for device init
        setTimeout(function () {
            newCanvas();
        }, 1000);

        // prevent footer to toggle on touch
        $("[data-role=footer]").fixedtoolbar({tapToggle: false});

        // reset palette selection (css) and select the clicked color for canvas strokeStyle
        $(".palette").click(function () {
            $(".palette").css("border-color", "#777");
            $(".palette").css("border-style", "solid");
            $(this).css("border-color", "#fff");
            $(this).css("border-style", "dashed");
            color = rgb2hex($(this).css("background-color"));
        });

        // link the new button with newCanvas() function
        $("#new").click(function () {
            sendDot(0, 0);
            newCanvas();
        });

        document.getElementById("content").style.height = window.innerHeight - 500;
        var canvas = '<canvas id="canvas" width="' + window.innerWidth + '" height="' + (window.innerHeight - 500) + '"></canvas>';
        document.getElementById("content").innerHTML = canvas;


        setInterval(function () {
            $.ajax({
                type: "GET",
                url: "https://" + window.location.hostname + ":" + $.cookie("api_port") + "/api/topicOnline",
                data: {
                    topic: "drawTopic"
                }, // serializes the form's elements.
                success: function (data) {
                    $("#title").html("Online:" + data.count);
                }
            });
        }, 2000);

        var pushClient = new PushClient("https://" + window.location.hostname + ":" + $.cookie("proxy_port"), {transports: ['websocket']});
        pushClient.subscribeTopic("drawTopic");

        pushClient.on('connect', function (data) {
            console.log("pushClient.on.connect ", data.uid, pushClient.pushId);
        });

        var lines = {};
        pushClient.on('push', function (data) {
            if (data.xPercent == 0 && data.yPercent == 0) {
                lines = {};
                newCanvas();
                dots = 0;
                return;
            }
            var line = lines[data.id];
            if (!line) {
                line = [];
                lines[data.id] = line;
            }
            line.push(data);
            dots++;
            //$("#title").html("Dots:" + dots);
            draw();
        });

        function draw() {
            var canvas = document.getElementById('canvas');
            var context = canvas.getContext('2d');
            context.clearRect(0, 0, canvas.width, canvas.height);
            var begin = false;
            for (var id in lines) {
                for (var line of lines[id]) {
                    context.lineWidth = 3;
                    if (line.color) {
                        context.strokeStyle = "#" + line.color;
                    }
                    if (!begin) {
                        context.beginPath();
                        context.moveTo(canvas.width * line.xPercent, canvas.height * line.yPercent);
                        begin = true;
                    } else if (line.endline) {
                        context.stroke();
                        begin = false;
                    } else {
                        context.lineTo(canvas.width * line.xPercent, canvas.height * line.yPercent);
                    }
                }
                if (begin) {
                    context.stroke();
                    begin = false;
                }
            }
        }

    });
    // function to setup a new canvas for drawing
    function newCanvas() {
        //define and resize canvas
        $("#content").height($(window).height() - 90);
        var canvas = '<canvas id="canvas" width="' + $(window).width() + '" height="' + ($(window).height() - 90) + '"></canvas>';
        $("#content").html(canvas);

        // setup canvas
//        ctx = document.getElementById("canvas").getContext("2d");
//        ctx.strokeStyle = color;
//        ctx.lineWidth = 5;

        // setup to trigger drawing on mouse or touch
        $("#canvas").drawTouch();
        $("#canvas").drawPointer();
        $("#canvas").drawMouse();
    }

    function sendDot(x, y, endline) {
        var canvas = document.getElementById('canvas');
        console.log(color.substring(1));
        if (y / canvas.height > 1 || y / canvas.height < 0) {
            return;
        }
        $.ajax({
            type: "POST",
            url: "https://" + window.location.hostname + ":" + $.cookie("api_port") + "/api/push",
            data: {
                topic: "drawTopic",
                json: JSON.stringify({
                    xPercent: x / canvas.width, yPercent: y / canvas.height,
                    color: color.substring(1), endline: endline,
                    id: id
                })
            }, // serializes the form's elements.
            success: function (data) {
            }
        });


    }
    // prototype to	start drawing on touch using canvas moveTo and lineTo
    $.fn.drawTouch = function () {
        var start = function (e) {
            e = e.originalEvent;
            x = e.changedTouches[0].pageX;
            y = e.changedTouches[0].pageY - 44;
            sendDot(x, y);
        };
        var move = function (e) {
            e.preventDefault();
            e = e.originalEvent;
            x = e.changedTouches[0].pageX;
            y = e.changedTouches[0].pageY - 44;
            sendDot(x, y);
        };
        var end = function (e) {
            e.preventDefault();
            e = e.originalEvent;
            x = e.changedTouches[0].pageX;
            y = e.changedTouches[0].pageY - 44;
            sendDot(x, y, true);
        };
        $(this).on("touchstart", start);
        $(this).on("touchmove", move);
        $(this).on("touchend", end);
    };

    // prototype to	start drawing on pointer(microsoft ie) using canvas moveTo and lineTo
    $.fn.drawPointer = function () {
        var start = function (e) {
            e = e.originalEvent;
            x = e.pageX;
            y = e.pageY - 44;
            sendDot(x, y);
        };
        var move = function (e) {
            e.preventDefault();
            e = e.originalEvent;
            x = e.pageX;
            y = e.pageY - 44;
            sendDot(x, y);
        };
        $(this).on("MSPointerDown", start);
        $(this).on("MSPointerMove", move);
    };
    // prototype to	start drawing on mouse using canvas moveTo and lineTo
    $.fn.drawMouse = function () {
        var clicked = 0;
        var start = function (e) {
            clicked = 1;
            x = e.pageX;
            y = e.pageY - 44;
            sendDot(x, y);
        };
        var move = function (e) {
            if (clicked) {
                x = e.pageX;
                y = e.pageY - 44;
                sendDot(x, y);
            }
        };
        var stop = function (e) {
            clicked = 0;
            x = e.pageX;
            y = e.pageY - 44;
            sendDot(x, y, true);
        };
        $(this).on("mousedown", start);
        $(this).on("mousemove", move);
        $(window).on("mouseup", stop);
    };

    var hexDigits = new Array
    ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f");

    //Function to convert hex format to a rgb color
    function rgb2hex(rgb) {
        rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
        return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
    }

    function hex(x) {
        return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
    }
</script>
</head>
<body>
<div data-role="page" id="page1">
    <div data-theme="a" data-role="header">
        <h3 id="title">Sketch Pad</h3>
        <a id="new" data-role="button" data-theme="b" class="ui-btn-left">New</a>
    </div>
    <div id="content"><p style="text-align:center">Loading Canvas...</p></div>
    <div data-theme="a" data-role="footer" data-position="fixed">
        <div class="palette-case">
            <div class="palette-box">
                <div class="palette white"></div>
            </div>
            <div class="palette-box">
                <div class="palette red"></div>
            </div>
            <div class="palette-box">
                <div class="palette blue"></div>
            </div>
            <div class="palette-box">
                <div class="palette green"></div>
            </div>
            <div class="palette-box">
                <div class="palette black"></div>
            </div>
            <div style="clear:both"></div>
        </div>
    </div>
</div>
</body>

</body>
</html>